package com.langChain4j.rag.service.impl;

import com.langChain4j.rag.service.EmbeddingStoreService;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.loader.UrlDocumentLoader;
import dev.langchain4j.data.document.parser.TextDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentByLineSplitter;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author linjun
 * @date 2025/9/29 10:18
 * @description
 */
@Service
public class EmbeddingStoreServiceImpl implements EmbeddingStoreService {

    @Autowired
    private EmbeddingStore<TextSegment> embeddingStore;

    @Autowired
    private EmbeddingModel embeddingModel;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appendByFile(String documentPath) {
        List<Document> documents = FileSystemDocumentLoader.loadDocuments(toPath(documentPath));
        EmbeddingStoreIngestor.builder().embeddingStore(embeddingStore)
                .embeddingModel(embeddingModel)
                .documentSplitter(new DocumentByLineSplitter(300,200))
                .build()
                .ingest(documents);
    }

    @Override
    public void appendByUrl(String url) {
        Document document = UrlDocumentLoader.load(url, new TextDocumentParser());
        EmbeddingStoreIngestor.builder().embeddingStore(embeddingStore)
                .embeddingModel(embeddingModel)
                .documentSplitter(new DocumentByLineSplitter(300,200))
                .build()
                .ingest(document);
    }

    public static Path toPath(String relativePath) {
        try {
            URL fileUrl = EmbeddingStoreServiceImpl.class.getClassLoader().getResource(relativePath);
            return Paths.get(fileUrl.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}
